﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections.Generic;
using Runda.CMS.Common.Utility;
using Runda.CMS.Common.Entity;
using Runda.CMS.Bll;
using Runda.CMS.Workflow;
using System.Text;
using Runda.CMS.Common.Exchange;

namespace Runda.CMS.Portal.Workspace
{
    public partial class ContractApprovalForFinance : WorkflowPage
    {
        public Guid ContractID
        {
            get
            {
                if (txtContractID.Value == "") return Guid.Empty;
                else return new Guid(txtContractID.Value);
            }
            set
            {
                txtContractID.Value = value.ToString();
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                listContractType.BindEnum(EnumeratorHelper.GetFieldTexts(typeof(Enumerator.ContractType)));

                List<SqlDbParameter> parms = new List<SqlDbParameter>();
                SqlDbParameter parm = new SqlDbParameter();
                parm.ColumnName = "Type";
                parm.ColumnType = DbType.Int32;
                parm.ParameterName = "@Type";
                parm.ParameterValue = System.Convert.ToInt32(ContractEnumerator.ContractParms.contractAttr);
                parm.QualificationType = SqlDbParameter.QualificationSymbol.Equal;
                parms.Add(parm);
                listContractAttribute.DataSource = new SysDictionaryBll().GetAll<SysDictionaryEntity>(parms);
                listContractAttribute.DataTextField = "Code";
                listContractAttribute.DataValueField = "ID";
                listContractAttribute.DataBind();

                if (Request.QueryString["BussinessID"] != null)
                {
                    ContractID = new Guid(Request.QueryString["BussinessID"].ToString());
                    txtTrackID.Value = Request.QueryString["TrackID"].ToString();
                    InitForm();
                }
            }
        }

        private void InitForm()
        {
            CtrtContractEntity entity = new CtrtContractEntity();
            CtrtContractBll bll = new CtrtContractBll();

            if (ContractID != Guid.Empty)
            {
                entity = bll.Get<CtrtContractEntity>(ContractID);
                txtContractCode.Text = entity.ContractCode;
                listContractAttribute.SelectedValue = entity.ContractAttribute.ToString();
                if (entity.ContractApplyDate != DateTime.MinValue)
                    txtContractApplyDate.SelectedDate = entity.ContractApplyDate;
                //if (entity.ContractEstimateSignDate != DateTime.MinValue)
                //    txtContractEstimateSignDate.SelectedDate = entity.ContractEstimateSignDate;
                listContractType.SelectedValue = entity.ContractType;
                txtContractStatement.Text = entity.ContractStatement;
                //txtContractPeriod.Text = entity.ContractPeriod.ToString();
                //txtGivenMaterialdesc.Text = entity.GivenMaterialdesc; 
                radtxtReachTo.Value = (double)entity.ReachTo;
                radtxtRebate.Value = (double)entity.Rebate;
                if (entity.InstanceID != Guid.Empty)
                {
                    BindWorkflow(entity.InstanceID);                  
                }
            }
        }

        protected void lnkbtnApprove_Click(object sender, EventArgs e)
        {
            //检查当前Track是否已审过
            WflInstanceRoutingBll InstanceRoutingBll = new WflInstanceRoutingBll();
            WflInstanceRoutingEntity TrackEntity = InstanceRoutingBll.Get<WflInstanceRoutingEntity>(new Guid(Request.QueryString["TrackID"]));
            if (TrackEntity != null)
            {
                if (TrackEntity.CheckStatus > 1)
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "saveandclose", "alert('该任务已审批过,不能重复审批!');window.close();", true);
                    return;
                }
            }
            else
            {
                ClientScript.RegisterStartupScript(this.GetType(), "saveandclose", "alert('参数有误');window.close();", true);
                return;
            }

            IWorkflowInstance instance = this.GetInstance(new Guid(Request.QueryString["TrackID"]), new Guid(Request.QueryString["TaskID"]));
            instance.OnNextRouting += new EventHandler<RoutingEventArgs>(instance_OnNextRouting);
            instance.Approve(txtComment.Text);

            //CtrtContractBll bll = new CtrtContractBll();
            //CtrtContractEntity entity = bll.Get<CtrtContractEntity>(ContractID);
            //entity.Status = (int)Enumerator.ContractStatus.Submit;
            //bll.Update(entity);
            ClientScript.RegisterStartupScript(this.GetType(), "saveandclose", "window.close();", true);
        }

        void instance_OnNextRouting(object sender, RoutingEventArgs e)
        {
            CtrtContractBll bll = new CtrtContractBll();
            CtrtContractEntity entity = bll.Get<CtrtContractEntity>(ContractID);
            StringBuilder sb = new StringBuilder();
            if (e.RoutingEntity.NextActivityID != Guid.Empty)
            {
                List<SqlDbParameter> parms = new List<SqlDbParameter>();
                SqlDbParameter parm = null;
                parm = new SqlDbParameter();
                parm.ColumnName = "ActivityID";
                parm.ColumnType = DbType.String;
                parm.ParameterName = "@ActivityID";
                parm.ParameterValue = e.RoutingEntity.NextActivityID;
                parm.QualificationType = SqlDbParameter.QualificationSymbol.Like;
                parms.Add(parm);

                WflActivityCheckersBll wacbll = new WflActivityCheckersBll();
                List<WflActivityCheckersEntity> list = wacbll.GetAll<WflActivityCheckersEntity>(parms);

                foreach (WflActivityCheckersEntity c in list)
                {
                    sb.Append(c.UserName).Append("(").Append(c.Account).Append(")").Append(",");
                    SysUserEntity userEntity = new SysUserBll().Get<SysUserEntity>(c.UserID);
                    //发送邮件给审核人
                    MailHandle.SendEmailNotice(base.CurrentUserEntity.UserName, userEntity.Email, "一份合同需要您的审核，合同编号：" + txtContractCode.Text.ToString() + "");
                }
                entity.NextCheckers = sb.ToString().TrimEnd(',');
            }
            else
            {
                entity.Status = (int)Enumerator.ContractStatus.Pass;
                entity.NextCheckers = string.Empty;

                //如果是变更合同,则更新原合同为作废状态
                if (entity.OriginalContractID != Guid.Empty)
                {
                    CtrtContractEntity OriginalEntity = bll.Get<CtrtContractEntity>(entity.OriginalContractID);
                    if (OriginalEntity != null)
                    {
                        OriginalEntity.Status = (int)Enumerator.ContractStatus.Nullify;
                        bll.Update(OriginalEntity);
                    }
                }
            }
            bll.Update(entity);
        }

        protected void lnkbtnReject_Click(object sender, EventArgs e)
        {
            //检查当前Track是否已审过
            WflInstanceRoutingBll InstanceRoutingBll = new WflInstanceRoutingBll();
            WflInstanceRoutingEntity TrackEntity = InstanceRoutingBll.Get<WflInstanceRoutingEntity>(new Guid(Request.QueryString["TrackID"]));
            if (TrackEntity != null)
            {
                if (TrackEntity.CheckStatus > 1)
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "saveandclose", "alert('该任务已审批过,不能重复审批!');window.close();", true);
                    return;
                }
            }
            else
            {
                ClientScript.RegisterStartupScript(this.GetType(), "saveandclose", "alert('参数有误');window.close();", true);
                return;
            }

            IWorkflowInstance instance = this.GetInstance(new Guid(Request.QueryString["TrackID"]), new Guid(Request.QueryString["TaskID"]));
            instance.Reject(txtComment.Text);

            CtrtContractBll bll = new CtrtContractBll();
            CtrtContractEntity entity = bll.Get<CtrtContractEntity>(ContractID);
            entity.NextCheckers = string.Empty;
            entity.Status = (int)Enumerator.ContractStatus.Back;
            bll.Update(entity);
            SysUserEntity userEntity = new SysUserBll().Get<SysUserEntity>(entity.CreatedBy);
            MailHandle.SendEmailNotice(base.CurrentUserEntity.UserName, userEntity.Email, "您提交的同被打回，合同编号：" + txtContractCode.ToString() + "");

            ClientScript.RegisterStartupScript(this.GetType(), "reject", "window.close();", true);
        }       

        private void BindWorkflow(Guid InstanceID)
        {
            List<WflInstanceRoutingEntity> list = new WflInstanceRoutingBll().GetAll<WflInstanceRoutingEntity>(" and InstanceID = '" + InstanceID + "' and CheckStatus != 1 order by CheckDate");

            RepeaterApprove.DataSource = list;
            RepeaterApprove.DataBind();
        }

        public string GetStatusText(int status)
        {
            string text = string.Empty;
            EnumeratorHelper[] cs = EnumeratorHelper.GetFieldTexts(typeof(Runda.CMS.Workflow.ActivityStatus));
            foreach (EnumeratorHelper c in cs)
            {
                if (c.EnumValue == status)
                {
                    text = c.EnumDisplayText; break;
                }
            }

            return text;
        }

        protected void btnSaveLeader_Click(object sender, EventArgs e)
        {
            CtrtContractEntity entity = new CtrtContractEntity();
            CtrtContractBll bll = new CtrtContractBll();
            entity = bll.Get<CtrtContractEntity>(ContractID);

            WflInstanceRoutingEntity TrackEntity = new WflInstanceRoutingBll().Get<WflInstanceRoutingEntity>(new Guid(Request.QueryString["TrackID"]));

            //添加一条Task 
            WflTaskBll TaskBll = new WflTaskBll();
            WflTaskEntity taskEntity = new WflTaskEntity();
            taskEntity.TaskID = Guid.NewGuid();
            taskEntity.Title = "您有一份合同需要填写意见";
            taskEntity.Entry = String.Concat("ContractComment.aspx", "?", "TrackID=", TrackEntity.TrackID, "&TaskID=", taskEntity.TaskID, "&BussinessID=", ContractID); 
            taskEntity.ActivityID = TrackEntity.ActivityID;
            taskEntity.Status = 0;
            taskEntity.TaskType = 1;
            TaskBll.Insert(taskEntity);

            WflCommentBll CommentBll = new WflCommentBll();
            WflCommentEntity  commentEntity = new WflCommentEntity();
            commentEntity.CreatedAt = DateTime.Now;
            commentEntity.InstanceID = entity.InstanceID;
            commentEntity.ActivityID = TrackEntity.ActivityID;
            commentEntity.Comments = string.Empty;
            commentEntity.LeaderID = Guid.Empty;// new Guid(ddlLeader.SelectedValue);

            CommentBll.InsertOrUpdate(commentEntity);
            SysUserEntity userEntity = new SysUserBll().Get<SysUserEntity>(commentEntity.LeaderID);
            MailHandle.SendEmailNotice(base.CurrentUserEntity.UserName, userEntity.Email, "您有一份合同需要填写意见，合同编号：" + txtContractCode.ToString() + "");

            ClientScript.RegisterStartupScript(this.GetType(), "reject", "alert('保存成功,请等待领导填写意见');window.close();", true);
        }
    }
}
